package sql

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
	"mallgo/internal/common/response"
	"mallgo/internal/resources/sql/api/domain/request"
	"mallgo/internal/resources/sql/resource"
	"net/http"
	"time"
)

type SqlController struct {
	limiter *rate.Limiter
}

func NewSqlController() *SqlController {
	limiter := rate.NewLimiter(rate.Every(200*time.Millisecond), 5) //// 使用限流器作为中间件
	return &SqlController{limiter}
}

func (c *SqlController) Query(ctx *gin.Context) {
	if c.limiter.Allow() == false {
		fmt.Println("====Disallow======", time.Now())
		ctx.JSON(http.StatusOK, response.Error(500, "请求过于频繁，请稍后再试"))
		return
	} else {
		fmt.Println("====Allow======", time.Now())
	}

	var req request.SqlRequest

	// 绑定并验证请求数据
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(200, response.Error(400, "请求参数错误"))
		return
	}
	res := resource.Query(&req)

	ctx.JSON(200, res)
}
